package com.icode.core.shared.usertype;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.StandardBasicTypes;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * User: alexz
 * Date: 15-1-20
 * Time: 下午4:40
 */
public class StringSetUserType extends AbstractHibernateUserType {

    @Override
    public int[] sqlTypes() {
        return new int[]{Types.VARCHAR};
    }

    @Override
    public Class returnedClass() {
        return Set.class;
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
        String value = (String) StandardBasicTypes.STRING.nullSafeGet(rs, names, session, owner);
        if (value == null) {
            return Collections.emptySet();
        }
        String[] values = value.split(DELIMITER);
        Set<String> results = new HashSet<>();
        for (String s : values) {
            results.add(s);
        }
        return results;
    }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
        if (value == null) {
            StandardBasicTypes.STRING.nullSafeSet(st, null, index, session);
        } else {
            Set<String> values = (Set<String>) value;
            String valueString = "";
            for (String s : values) {
                valueString += s + DELIMITER;
            }
            valueString = valueString.substring(0, valueString.lastIndexOf(DELIMITER));
            StandardBasicTypes.STRING.nullSafeSet(st, valueString, index, session);
        }
    }
}
